<template>
  <div>
    <el-card class="margin-top">
      <div slot="header" class="clearfix">
        <span class="title-icon margin-right-sm">{{
          $t('waybill.ThePackingList')
        }}</span>
        <el-tooltip placement="top" effect="light">
          <div slot="content">
            应进出口国海关要求，装箱单必须做到每箱的箱号要与该箱内所装产品的SKU号码准确对应。
            <br />如申报的装箱明细与实际装箱明细不符，在遇到海关查验时，可能产生延误、扣关甚至罚款等责任，将由您自行承担！
          </div>
          <i class="el-icon-question icon-question text-yellow" />
        </el-tooltip>
        <el-button
          class="margin-lr"
          size="mini"
          type="success"
          @click="resetPacking"
        >
          重置装箱单
        </el-button>

        <span v-html="showTips" />
      </div>

      <template v-if="packingList.length > 0">
        <div
          v-for="(item, index) in packingList"
          :key="index"
          class="margin-top"
        >
          <el-row :gutter="20" type="flex" class="align-center">
            <el-col :span="5" class="flex align-center justify-start">
              <i
                style="font-size:26px"
                :class="{
                  'el-icon-arrow-down': item.show,
                  'el-icon-arrow-up': !item.show
                }"
                @click="toggleTable(item)"
              />
              <span v-if="item.shipmentId" class="margin-left">
                ShipmentID:{{ item.shipmentId }}
              </span>
            </el-col>
            <el-col :span="4">
              <div class="flex align-center justify-start">
                <span class="head-title">箱号规则：</span>
                <el-select
                  v-model="item.rule"
                  placeholder="请选择"
                  size="mini"
                  @change="
                    val => {
                      changeRule(val, item)
                    }
                  "
                >
                  <el-option
                    v-for="(optionItem, optionIndex) in rulesNo"
                    :key="optionIndex"
                    :label="optionItem"
                    :value="optionItem"
                  />
                </el-select>
              </div>
            </el-col>
            <el-col :span="4">
              <div class="flex align-center justify-start">
                <span class="head-title">
                  起始箱号：
                </span>
                <el-tooltip class="item" effect="light" placement="top-end">
                  <div slot="content">
                    起始箱号为1，不填写结束箱号，则是填写1箱的数据。
                    <br />起始箱号为1，结束箱号为1，则是填写1箱的数据。
                    <br />起始箱号为1，结束箱号为2，则是填写2箱的数据。
                  </div>
                  <el-input
                    v-model="item.startBoxNo"
                    class="flex-treble"
                    type="number"
                    size="mini"
                    placeholder="请填写起始箱号"
                    maxlength="4"
                    max="9999"
                    min="1"
                    @input="
                      item.startBoxNo.length > 4
                        ? (item.startBoxNo = item.startBoxNo.slice(0, 4))
                        : item.startBoxNo
                    "
                  />
                </el-tooltip>
              </div>
            </el-col>
            <el-col :span="4">
              <div class="flex align-center justify-center">
                <span class="head-title">结束箱号：</span>

                <el-input
                  v-model="item.endBoxNo"
                  class="flex-treble"
                  type="number"
                  size="mini"
                  maxlength="4"
                  max="9999"
                  min="0"
                  placeholder="请填写结束箱号,例如 2"
                  @input="
                    item.startBoxNo.length > 4
                      ? (item.startBoxNo = item.startBoxNo.slice(0, 4))
                      : item.startBoxNo
                  "
                />
              </div>
            </el-col>
            <el-col :span="7">
              <el-button
                type="primary"
                size="mini"
                @click.native="selectSKU(item, index)"
              >
                选择SKU
              </el-button>
              <el-button
                type="primary"
                size="mini"
                @click.native="delSelectSKU(index)"
              >
                批量删除
              </el-button>
              <el-button
                type="primary"
                size="mini"
                @click.native="batchEditSelectSKU(index)"
              >
                批量编辑
              </el-button>
            </el-col>
          </el-row>
          <!-- :span-method="objectSpanMethod" -->
          <el-collapse-transition>
            <el-table
              v-show="item.show"
              ref="multipleTable"
              :header-cell-style="{ background: '#f5f9fc' }"
              size="mini"
              border
              :data="item.tableData"
              :span-method="objectSpanMethod"
              style="width: 100%;"
              class="margin-top "
              tooltip-effect="light"
              @selection-change="handleSelectionChange($event, index)"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column
                label="箱号"
                align="center"
                prop="cartonNo"
                width="200"
              />
              <el-table-column
                prop="grossWeight"
                label="单箱毛重(kg)"
                align="center"
              />
              <el-table-column prop="LWH" label="长×宽×高(cm)" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.length }}</span>
                  <span v-if="scope.row.length">X</span>
                  <span>{{ scope.row.width }}</span>
                  <span v-if="scope.row.width">X</span>
                  <span>{{ scope.row.height }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="skuName"
                label="SKU"
                align="center"
                min-width="400"
                show-overflow-tooltip
              />
              <el-table-column
                prop="declareNameCn"
                label="中文品名"
                align="center"
                min-width="260"
                show-overflow-tooltip
              />
              <el-table-column
                prop="skuNum"
                label="个数"
                align="center"
                min-width="50"
              />
              <el-table-column label="" width="50" align="center">
                <template slot-scope="scope">
                  <!-- <el-popconfirm
                    title="确定删除吗？"
                    @onConfirm="handleDelete(index, scope.$index, scope.row)"
                  > -->
                  <i
                    class="el-icon-delete padding-lr-sm pointer"
                    @click="handleDelete(index, scope.$index, scope.row)"
                  />
                  <!-- </el-popconfirm> -->
                </template>
              </el-table-column>
              <el-table-column label="编辑" width="60" align="center">
                <template slot-scope="scope">
                  <i
                    class="el-icon-edit padding-lr-sm pointer"
                    @click="handleEdit(index, scope.$index, scope.row)"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-transition>
        </div>
      </template>
    </el-card>

    <!--  -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="showSelectDialog"
      :close="hideSelectDialog"
      width="60%"
    >
      <div v-if="packingList && packingList[showIndex]" class="dialog-main">
        <p class="text-center">
          {{ dialogHead }}
        </p>

        <el-table
          :ref="`selectTable${showIndex}`"
          :data="selectTable"
          max-height="500"
          tooltip-effect="light"
        >
          <el-table-column type="index" label="序号" width="60" />

          <el-table-column property="skuName" label="SKU" width="300" />
          <el-table-column
            property="declareNameCn"
            label="中文品名"
            show-overflow-tooltip
          />
          <el-table-column property="skuNum" label="总个数" />
          <el-table-column label="剩余个数">
            <template slot-scope="scope">
              {{ updateRemainingNum(scope, showIndex) }}
              <!-- {{ scope.row.skuNum - scope.row.packingNum - scope.row.inputNum }} -->
            </template>
          </el-table-column>
          <el-table-column
            :label="dialogTitle === '选择SKU' ? '装入每箱数量' : '装入该箱数量'"
          >
            <template slot-scope="scope">
              <el-input
                v-model.number="scope.row.inputNum"
                type="number"
                min="0"
                placeholder="请填写数量"
                @input="remainingNum(scope, showIndex, packingList[showIndex])"
              />
            </template>
          </el-table-column>
        </el-table>
        <el-form class="margin-top" :model="dialogInfo" :rules="dialogRule">
          <el-row>
            <el-col :span="8">
              <el-form-item label-width="110px" prop="grossWeight">
                <div slot="label">单箱毛重(KG):</div>

                <el-input v-model.trim="dialogInfo.grossWeight" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="16" class="flex ">
              <div
                class="flex-sub form-input-length text-right padding-right-sm"
              >
                <span>单箱长X宽X高(cm):</span>
              </div>

              <el-row :gutter="10" class="flex-twice">
                <el-col :span="7">
                  <el-form-item prop="length" label-width="0">
                    <el-input
                      v-model.trim="dialogInfo.length"
                      placeholder="长"
                      @input="changeLength"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="1" class="form-input-length">X</el-col>
                <el-col :span="7">
                  <el-form-item prop="width" label-width="0">
                    <el-input
                      v-model.trim="dialogInfo.width"
                      placeholder="宽"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="1" class="form-input-length">X</el-col>
                <el-col :span="7">
                  <el-form-item prop="height" label-width="0">
                    <el-input
                      v-model.trim="dialogInfo.height"
                      placeholder="高"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideSelectDialog">取 消</el-button>
        <el-button
          v-if="dialogTitle === '选择SKU'"
          type="primary"
          @click="enterSelectSku"
        >
          确 定
        </el-button>
        <el-button v-else type="primary" @click="editSelectSku">
          确 定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="showSelectDialog2"
      :close="hideSelectDialog"
      width="60%"
    >
      <div v-if="packingList && packingList[showIndex]" class="dialog-main">
        <el-table
          :data="multipleSelection"
          max-height="500"
          tooltip-effect="light"
        >
          <el-table-column type="index" label="序号" width="60" />

          <el-table-column
            label="箱号"
            align="center"
            prop="cartonNo"
            width="200"
          />

          <el-table-column
            prop="skuName"
            label="SKU"
            align="center"
            min-width="300"
            show-overflow-tooltip
          />

          <el-table-column label="装入该箱数量">
            <template slot-scope="scope">
              {{ scope.row.skuNum }}
              <!-- <el-input
                v-model.number="scope.row.skuNum"
                type="number"
                min="0"
                placeholder="请填写数量"
                @input="remainingNum(scope, showIndex, packingList[showIndex])"
              /> -->
            </template>
          </el-table-column>
        </el-table>
        <el-form class="margin-top" :model="dialogInfo" :rules="dialogRule">
          <el-row>
            <el-col :span="8">
              <el-form-item label-width="110px" prop="grossWeight">
                <div slot="label">单箱毛重(KG):</div>

                <el-input v-model.trim="dialogInfo.grossWeight" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="16" class="flex ">
              <div
                class="flex-sub form-input-length text-right padding-right-sm"
              >
                <span>单箱长X宽X高(cm):</span>
              </div>

              <el-row :gutter="10" class="flex-twice">
                <el-col :span="7">
                  <el-form-item prop="length" label-width="0">
                    <el-input
                      v-model.trim="dialogInfo.length"
                      placeholder="长"
                      @input="changeLength"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="1" class="form-input-length">X</el-col>
                <el-col :span="7">
                  <el-form-item prop="width" label-width="0">
                    <el-input
                      v-model.trim="dialogInfo.width"
                      placeholder="宽"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="1" class="form-input-length">X</el-col>
                <el-col :span="7">
                  <el-form-item prop="height" label-width="0">
                    <el-input
                      v-model.trim="dialogInfo.height"
                      placeholder="高"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideSelectDialog">取 消</el-button>

        <el-button type="primary" @click="editSelectSku2">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { clone } from '@/utils/clone'
import { getSpanArr, changeCartonNo } from '@/utils/invoice-table'
export default {
  name: 'PackingList',
  filters: {
    sliceName(name) {
      if (!name) return ''
      return name.slice(2)
    }
  },
  props: {
    packingListInfo: {
      type: Array,
      default: function() {
        return []
      }
    },
    showTips: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogTitle: '选择SKU',
      dialogHead: '选择SKU',
      showRowIndex: 0,
      packingList: [],
      showSelectDialog: false,
      showSelectDialog2: false,
      multipleSelection: [],
      rulesNo: ['U001', 'U0001', 'U00001', 'U000001'],
      spanArr: [],
      tableData: [],
      showIndex: '',
      selectTableData: {},
      dialogInfo: {
        length: '',
        width: '',
        height: '',
        grossWeight: ''
      },
      selectTable: [],
      dialogRule: {
        length: [
          { required: false, message: '请填写正整数', trigger: 'blur' },
          {
            pattern: /^[+]?\d*\.?\d{0,3}$/,
            message: '须为数字,可留3位小数'
          }
        ],
        width: [
          { required: false, message: '请填写正整数', trigger: 'blur' },
          {
            pattern: /^[+]?\d*\.?\d{0,3}$/,
            message: '须为数字,可留3位小数'
          }
        ],
        height: [
          { required: false, message: '请填写正整数', trigger: 'blur' },
          {
            pattern: /^[+]?\d*\.?\d{0,3}$/,
            message: '须为数字,可留3位小数'
          }
        ],
        grossWeight: [
          { required: false, message: '请填写正整数', trigger: 'blur' },
          {
            pattern: /^[+]?\d*\.?\d{0,3}$/,
            message: '须为数字,可留3位小数'
          }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['invoiceInfo', 'channelFormLeft', 'packingInfo']),
    updateRemainingNum() {
      return function(scope, index) {
        let num = 1
        const p = this.packingList[index]
        if (this.dialogTitle === '选择SKU') {
          num =
            1 -
            parseInt(p.startBoxNo) +
            parseInt(p.endBoxNo ? p.endBoxNo : p.startBoxNo)
          return (
            scope.row.skuNum - scope.row.packingNum - scope.row.inputNum * num
          )
        } else {
          return scope.row.skuNum - scope.row.packingNum - scope.row.inputNum
        }
      }
    }
  },
  watch: {
    packingInfo: {
      handler(newVal, oldVal) {
        // console.log('newVal :>> ', newVal)
        this.packingList = this.packingInfo
      }
    },
    packingList: {
      handler(nVal, oVal) {
        if (!nVal) return
        this.$store.dispatch(
          'createWaybill/changePackingInfo',
          this.packingList
        )
        this.$emit('update:packingListInfo', nVal)
      }
    }
  },
  mounted() {
    // this.getSpanArr(this.tableData)
    // 提取缓存
    // if (this.packingInfo.length > 0) {
    //   this.packingList = this.packingInfo
    // }
  },
  methods: {
    resetPacking() {
      this.$emit('resetPacking')
    },
    changeLength(val) {
      console.log('val :>> ', val)
    },
    // 弹出框标题
    dialogHeadFn() {
      // if (!this.showIndex) return
      let head = ''
      const p = this.packingList[this.showIndex]
      if (this.dialogTitle === '选择SKU') {
        const cartonNo =
          p.rule.slice(0, p.rule.length - p.startBoxNo.toString().length) +
          p.startBoxNo

        head = `箱号：${cartonNo} - ${p.endBoxNo ? p.endBoxNo : p.startBoxNo} 共
          ${1 -
            parseInt(p.startBoxNo) +
            parseInt(p.endBoxNo ? p.endBoxNo : p.startBoxNo)}箱`
      } else {
        const num = p.tableData[this.showRowIndex].cartonNo

        head = `箱号 ${num}`
      }

      this.dialogHead = head
    },
    // 判断剩余数量是否足够
    remainingNum(scope, index, data) {
      console.log('scope.row :>> ', scope.row)
      let num = 1
      const p = this.packingList[index]
      if (this.dialogTitle === '选择SKU') {
        num =
          parseInt(scope.row.skuNum) -
          parseInt(scope.row.packingNum) -
          parseInt(scope.row.inputNum) *
            (1 -
              parseInt(p.startBoxNo) +
              parseInt(p.endBoxNo ? p.endBoxNo : p.startBoxNo))
        if (num < 0) {
          this.$message.error('SKU个数超过剩余个数')
          scope.row.inputNum = '0'
          return parseInt(scope.row.skuNum)
        } else {
          return parseInt(num)
        }
      } else {
        num =
          parseInt(scope.row.skuNum) -
          parseInt(scope.row.packingNum) -
          parseInt(scope.row.inputNum)
        console.log('num :>> ', num)
        if (num < 0) {
          this.$message.error('SKU个数超过剩余个数')
          scope.row.inputNum = '0'
          return parseInt(scope.row.skuNum)
        } else {
          return parseInt(num)
        }
      }
    },
    handleSelectionChange(val, index) {
      console.log('val :>> ', val)
      console.log('index :>> ', index)
      // this.packingList[index].multipleSelection = val
      const arr = []
      for (const i of val) {
        arr.push(i.cartonNo)
      }
      this.$delete(this.packingList[index], 'multipleSelection')
      this.$set(this.packingList[index], 'multipleSelection', val)
    },
    async delSelectSKU(index) {
      console.log(
        'this.packingList[index] :>> ',
        this.packingList[index].multipleSelection
      )
      const obj = clone(this.packingList[index])
      if (!obj.multipleSelection || obj.multipleSelection.length === 0) {
        this.$message.error('请选择要删除的数据！')
        return
      }

      const table = clone(obj.tableData)
      console.log('table :>> ', table)

      for (const j of obj.multipleSelection) {
        for (let i = table.length - 1; i >= 0; i--) {
          if (table[i].cartonNo === j.cartonNo) {
            table.splice(i, 1)
          }
        }
      }

      obj.tableData = table
      for (const i of obj.filterData) {
        for (const j of obj.multipleSelection) {
          if (i.skuName === j.skuName) {
            i.packingNum -= j.skuNum
          }
        }
      }

      if (
        this.packingList[index].tableData.length > 1 &&
        obj.multipleSelection.length !==
          this.packingList[index].tableData.length
      ) {
        this.$set(this.packingList, index, await getSpanArr(obj))
      } else {
        this.$set(this.packingList, index, obj)
      }
    },
    batchEditSelectSKU(index) {
      console.log(
        'this.packingList[index] :>> ',
        this.packingList[index].multipleSelection
      )
      const obj = clone(this.packingList[index])
      if (!obj.multipleSelection || obj.multipleSelection.length === 0) {
        this.$message.error('请选择要编辑的数据！')
        return
      }

      console.log('obj :>> ', obj)

      this.showIndex = index
      // this.showRowIndex = rowIndex
      this.dialogTitle = '编辑箱单SKU'
      this.dialogHeadFn()
      const arr = []
      const nameArr = []
      this.multipleSelection = obj.multipleSelection
      // console.log('targetData :>> ', targetData)
      // 回显 长宽高 毛重
      this.dialogInfo.length = this.multipleSelection[0].length
      this.dialogInfo.width = this.multipleSelection[0].width
      this.dialogInfo.height = this.multipleSelection[0].height
      this.dialogInfo.grossWeight = this.multipleSelection[0].grossWeight
      //
      // for (const i of this.packingList[index].tableData) {
      //   const target = this.multipleSelection.find(
      //     x => x.cartonNo === i.cartonNo
      //   )
      //   if (target) {
      //     arr.push(i)
      //     nameArr.push(i.skuName)
      //   }
      // }

      console.log('arr :>> ', arr)
      //  当前选中的表格数据
      // this.selectTableData = {
      //   data: arr,
      //   nameArr: nameArr
      // }

      // this.selectTable = clone(this.packingList[index].filterData)
      // 初始化 输入数量
      // this.selectTable.forEach(i => {
      //   i.inputNum = '0'
      // })
      //
      // for (const j of this.selectTableData.data) {
      //   for (const i of this.selectTable) {
      //     if (i.skuName === j.skuName) {
      //       const num = clone(i.packingNum)
      //       i.inputNum = j.skuNum
      //       i.packingNum = num - j.skuNum
      //     }
      //   }
      // }

      this.showSelectDialog2 = true
    },
    // 计算表格合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (
        columnIndex === 0 ||
        columnIndex === 1 ||
        columnIndex === 2 ||
        columnIndex === 3 ||
        columnIndex === 8
      ) {
        if (!(row.shipmentId === '' || row.shipmentId)) {
          // console.log('表格合并缺乏shipmentId :>> ')
        }
        // 关键字段  shipmentId 一定要存在
        const target = this.packingList.find(
          x => x.shipmentId === row.shipmentId
        )
        // console.log('target.spanArr[rowIndex] :>> ', target.spanArr[rowIndex])
        const row_span =
          target && (target.spanArr[rowIndex] || target.spanArr[rowIndex] === 0)
            ? target.spanArr[rowIndex]
            : 1
        return {
          rowspan: row_span,
          colspan: 1
        }
      }
    },
    handleEdit(index, rowIndex, row) {
      // console.log(index, rowIndex, row)
      this.showIndex = index
      this.showRowIndex = rowIndex
      this.dialogTitle = '编辑箱单SKU'
      this.dialogHeadFn()
      const arr = []
      const nameArr = []
      const targetData = this.packingList[index].tableData[rowIndex]
      // console.log('targetData :>> ', targetData)
      // 回显 长宽高 毛重
      this.dialogInfo.length = targetData.length
      this.dialogInfo.width = targetData.width
      this.dialogInfo.height = targetData.height
      this.dialogInfo.grossWeight = targetData.grossWeight
      //
      for (const i of this.packingList[index].tableData) {
        if (i.cartonNo === targetData.cartonNo) {
          arr.push(i)
          nameArr.push(i.skuName)
        }
      }
      //  当前选中的表格数据
      this.selectTableData = {
        data: arr,
        nameArr: nameArr
      }

      this.selectTable = clone(this.packingList[index].filterData)
      console.log('this.selectTable :>> ', this.selectTable)
      // 初始化 输入数量
      this.selectTable.forEach(i => {
        i.inputNum = '0'
      })
      //
      for (const j of this.selectTableData.data) {
        for (const i of this.selectTable) {
          if (i.skuName === j.skuName) {
            const num = clone(i.packingNum)
            i.inputNum = j.skuNum
            i.packingNum = num - j.skuNum
          }
        }
      }

      this.showSelectDialog = true
    },
    // 删除数据
    async handleDelete(index, rowIndex, row) {
      console.log('index :>> ', index)
      console.log('rowIndex :>> ', rowIndex)
      console.log('row :>> ', row)
      this.showIndex = index
      this.showRowIndex = rowIndex
      const obj = Object.assign({}, this.packingList[index])
      // console.log('this.packingList[index] :>> ', this.packingList[index])

      const arr = obj.tableData.filter((val, j) => {
        if (j !== rowIndex) {
          return val
        }
      })
      obj.tableData = arr
      for (const i of obj.filterData) {
        if (i.skuName === row.skuName) {
          i.packingNum -= row.skuNum
        }
      }
      // console.log('obj :>> ', obj)
      // console.log('this.packingList[index] :>> ', this.packingList[index])

      if (this.packingList[index].tableData.length > 1) {
        this.$set(this.packingList, this.showIndex, await getSpanArr(obj))
      } else {
        this.$set(this.packingList, this.showIndex, obj)
      }
    },
    toggleTable(item) {
      console.log(item)
      const flag = !item.show
      this.$delete(item, 'show')
      this.$set(item, 'show', flag)
    },
    selectSKU(item, index) {
      this.dialogTitle = '选择SKU'
      // 清除上一次输入的 长宽高 毛重
      item.length = ''
      item.width = ''
      item.height = ''
      item.grossWeight = ''

      // 箱号.length == 箱数
      const cartonNoList = []
      for (const i of this.packingList[index].tableData) {
        if (!cartonNoList.includes(i.cartonNo)) {
          cartonNoList.push(i.cartonNo)
        }
      }

      if (
        item.rule === 'U001' &&
        parseInt(item.endBoxNo) -
          parseInt(item.startBoxNo) +
          cartonNoList.length >
          999
      ) {
        this.$notify.error({
          title: '箱号规则U001 ',
          message: '总箱数不能大于999！',
          position: 'bottom-right'
        })
      } else if (
        item.rule !== 'U001' &&
        parseInt(item.endBoxNo) -
          parseInt(item.startBoxNo) +
          cartonNoList.length >
          10000
      ) {
        this.$notify.error({
          title: `箱号规则${item.rule}`,
          message: '总箱数不能大于10000！',
          position: 'bottom-right'
        })
      } else if (
        item.startBoxNo &&
        item.endBoxNo &&
        parseInt(item.endBoxNo) - parseInt(item.startBoxNo) < 0
      ) {
        this.$notify.error({
          title: '请正确填写开始和结束箱号',
          message: '起始箱号不能大于结束箱号！',
          position: 'bottom-right'
        })
        return
      } else if (
        item.startBoxNo
        // item.endBoxNo &&
        // parseInt(item.endBoxNo) - parseInt(item.startBoxNo) >= 0 &&
        // parseInt(item.endBoxNo) -
        //   parseInt(item.startBoxNo) +
        //   cartonNoList.length <
        //   3000
      ) {
        this.showSelectDialog = true
        // 当前选中 箱单
        this.showIndex = index
        this.selectTable = clone(this.packingList[index].filterData)
      } else {
        this.$notify.error({
          title: '请正确填写开始和结束箱号',
          message: '箱号为正整数',
          position: 'bottom-right'
        })
        return
      }
      this.dialogHeadFn()
    },
    hideSelectDialog() {
      // console.log(
      //   '%chideSelectDialog: ',
      //   'color: MidnightBlue; background: Aquamarine;'
      // )
      this.showSelectDialog = false
      this.showSelectDialog2 = false
      this.dialogInfo = {
        length: '',
        width: '',
        height: '',
        grossWeight: ''
      }
      this.selectTable = []
      this.packingList[this.showIndex].filterData.forEach(i => {
        i.inputNum = '0'
      })
      this.showRowIndex = ''
    },

    // 选择SKU
    async enterSelectSku() {
      /**
       * 1.获取表单现有得数据，相同箱号，SKU的数据进行数据修改；相同箱号不同SKU进行 合并
       */
      const obj = Object.assign({}, this.packingList[this.showIndex])
      console.log('obj :>> ', obj)
      // 获取箱数
      const startBoxNo = parseInt(obj.startBoxNo)
      const endBoxNo = parseInt(obj.endBoxNo ? obj.endBoxNo : obj.startBoxNo)
      const rowNum = 1 - (startBoxNo - endBoxNo)
      const arrayList = []
      // 修改已填写箱数
      for (const i of this.selectTable) {
        console.log('parseInt(i.inputNum) :>> ', parseInt(i.inputNum))
        if (!i.inputNum) {
          this.$message.error('请填写填装数量！')
          return
        }

        if (parseInt(i.inputNum) === 0) {
          continue
        }

        // 修改对应数据 packingNum
        const target = this.packingList[this.showIndex].filterData.find(
          x => x.skuName === i.skuName
        )
        target.packingNum =
          parseInt(i.inputNum * rowNum) +
          (i.packingNum ? parseInt(i.packingNum) : 0)

        // 生成的表格数据
        for (let index = 0; index < rowNum; index++) {
          if (parseInt(i.inputNum) !== 0) {
            // 获取箱号
            const boxNum = (startBoxNo + index).toString()
            const ruleStr =
              obj.rule.slice(0, obj.rule.length - boxNum.length) + boxNum
            // 箱号
            const cartonNo = `${obj.shipmentId + ruleStr}`
            const data = {
              shipmentId: obj.shipmentId,
              cartonNo: cartonNo,
              grossWeight: this.dialogInfo.grossWeight,
              length: this.dialogInfo.length,
              height: this.dialogInfo.height,
              width: this.dialogInfo.width,
              skuName: i.skuName,
              declareNameCn: i.declareNameCn,
              declareNameEn: i.declareNameEn,
              skuNum: i.inputNum
            }
            arrayList.push(data)
          }
        }

        i.inputNum = '0'
      }

      this.dialogInfo = {
        length: '',
        width: '',
        height: '',
        grossWeight: ''
      }

      await this.checkData(arrayList)
    },
    // 编辑SKU
    editSelectSku() {
      const arr = []
      const obj = this.selectTable

      for (const i of obj) {
        for (const j of this.selectTableData.data) {
          // 同数据，数量改变
          if (i.skuName === j.skuName) {
            j.shipmentId = this.packingList[this.showIndex].shipmentId
            j.grossWeight = this.dialogInfo.grossWeight
            j.length = this.dialogInfo.length
            j.height = this.dialogInfo.height
            j.width = this.dialogInfo.width
            j.skuNum = i.inputNum
            const target = this.packingList[this.showIndex].filterData.find(
              x => x.skuName === i.skuName
            )
            target.packingNum = i.inputNum + i.packingNum
          }

          // 表格中不存在，新增的数据
          if (
            i.inputNum > 0 &&
            !this.selectTableData.nameArr.includes(i.skuName)
          ) {
            // console.log('表格中不存在，新增的数据 :>> ', obj)
            this.selectTableData.nameArr.push(i.skuName)
            i.packingNum = i.inputNum

            const data = {
              cartonNo: j.cartonNo,
              grossWeight: this.dialogInfo.grossWeight,
              shipmentId: this.packingList[this.showIndex].shipmentId,
              length: this.dialogInfo.length,
              height: this.dialogInfo.height,
              width: this.dialogInfo.width,
              skuName: i.skuName,
              declareNameCn: i.declareNameCn,
              declareNameEn: i.declareNameEn,
              skuNum: i.inputNum
            }
            arr.push(data)
          }
        }
      }

      // console.log('this.selectTableData :>> ', this.selectTableData)

      this.checkData(arr)
      this.dialogInfo = {
        length: '',
        width: '',
        height: '',
        grossWeight: ''
      }
      this.selectTable = []
    },
    editSelectSku2() {
      for (const i of this.packingList[this.showIndex].tableData) {
        const t = this.multipleSelection.find(x => x.cartonNo === i.cartonNo)
        if (t) {
          this.$set(i, 'grossWeight', this.dialogInfo.grossWeight)
          this.$set(i, 'length', this.dialogInfo.length)
          this.$set(i, 'height', this.dialogInfo.height)
          this.$set(i, 'width', this.dialogInfo.width)
        }
      }

      this.dialogInfo = {
        length: '',
        width: '',
        height: '',
        grossWeight: ''
      }
      this.showSelectDialog2 = false
    },
    async checkData(arr) {
      if (arr.length === 0) {
        this.hideSelectDialog()
        return
      }
      const d = clone(this.packingList[this.showIndex])
      d.tableData = [...d.tableData, ...arr]
      // 合并相同箱号 同一sku 数据
      const combined = d.tableData.reduce((acc, cur) => {
        const target = acc.find(
          e => e.cartonNo === cur.cartonNo && e.skuName === cur.skuName
        )
        if (target) {
          // 存在相同，skunum相加
          target.skuNum += cur.skuNum
        } else {
          acc.push(cur)
        }
        return acc
      }, [])

      console.log('combined :>> ', combined)
      this.packingList[this.showIndex].tableData = combined
      this.$set(
        this.packingList,
        this.showIndex,
        await getSpanArr(this.packingList[this.showIndex])
      )
      // await getSpanArr(this.packingList[this.showIndex])

      this.hideSelectDialog()
    },
    async changeRule(val, item) {
      // item.rule
      // '当前箱号序号大于999,不能使用U001箱号规则,请重选箱号规则'
      const data = item.tableData
      if (
        val === 'U001' &&
        data.length > 0 &&
        data[data.length - 1].cartonNo.slice(3) > 999
      ) {
        this.$alert(
          '当前箱号序号大于999,不能使用U001箱号规则,请重选箱号规则',
          'U001箱号规则',
          {
            confirmButtonText: '确定',
            callback: action => {
              item.rule = item.oldRule
            }
          }
        )
      } else {
        item.rule = val
        item.oldRule = val
        Object.assign(item, await changeCartonNo(item))
      }
    }
  }
}
</script>

<style scoped>
.el-select {
  width: calc(100% - 70px);
}
</style>

<style lang="scss" scoped>
.head-title {
  width: 70px;
}

.form-input-length {
  line-height: 36px;
}
</style>
